package com.cpj.filter;


import org.slf4j.MDC;

import javax.servlet.*;
import java.io.IOException;
import java.util.UUID;

/**
 * 增加输出日志traceRootId
 */
public class LogbackFilter implements Filter {

    private static final String UNIQUE_ID = "traceRootId";


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        boolean bInsertMDC = insertMDC();
        try {
            chain.doFilter(request, response);
        } finally {
            if (bInsertMDC) {
                removeAll();
            }
        }
    }

    private void removeAll(){
        try {
            MDC.remove(UNIQUE_ID);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private boolean insertMDC() {
        try {
            UUID uuid = UUID.randomUUID();
            String uniqueId = uuid.toString().replace("-", "");
            MDC.put(UNIQUE_ID, uniqueId);
            return true;

        }catch (Exception e){
            e.printStackTrace();
        }
       return false;
    }

    @Override
    public void destroy() {

    }

}